// owner-app/pages/formresident-my-dwelldetail/index.js
import {
  handlerGobackClick,
  hint,
  checkIDCard,
  checkPhone,
  formatters,
} from "../../../utils/util";
const app = getApp();
import Apipublic from "../../../models/api";
const apipublic = new Apipublic();
import CompleteInfor from "../../../models/completeInformation";
const completeInfor = new CompleteInfor();
import User from "../../../models/user";
const user = new User();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    stepsActice: 0,
    stepsList: [
      { text: "身份信息" },
      { text: "居住地址" },
      { text: "门禁信息" },
    ],
    baseImgUrl: "",
    userType: "",
    timea: new Date().getTime(),
    //身份信息表单
    name: "",
    typesOfCertificateDesc: "",
    identificationNumber: "",
    sexDesc: "", //性别 (居民身份证和外籍人员共用一个性别字段)
    nationDesc: "",
    permanentAddress: "",
    birthDate: "",
    countryDesc: "",
    entryTime: "",
    validityTerm: "",
    //身份信息表单对应弹框
    typesOfCertificateShow: false,
    sexShow: false,
    nationShow: false,
    birthDateShow: false,
    entryTimeShow: false,
    validityTermShow: false,
    countryDescShow: false,
    minDate: new Date(1920, 0, 1).getTime(),
    maxDate: new Date().getTime(),
    minTermDate: new Date(1920, 0, 1).getTime(),
    formatter(type, value) {
      if (type === "year") {
        return `${value}年`;
      } else if (type === "month") {
        return `${value}月`;
      }
      return value;
    },
    //居住信息表单
    minDateday: new Date(2000, 0, 1).getTime(),
    maxDateday: new Date(2099, 0, 1).getTime(),
    currAdd: "",
    kinshipDesc: "",
    startDate: "",
    endDate: "",
    startDateDesc: "",
    endDateDesc: "",
    phoneNum: "",
    houseCategoryDesc: "",
    houseNatureDesc: "",
    houseUseDesc: "",
    houseStatusDesc: "",
    houseStructDesc: "",
    houseCount: "",
    area: "",
    isRent: "",
    rentCount: "",
    rentArea: "",
    rentUseDesc: "",
    houseTypeDesc: "",
    houseCard: "",
    //居住信息表单对应弹框
    floorNameShow: false,
    kinshipDescShow: false,
    startDateShow: false,
    endDateShow: false,
    houseCategoryDescShow: false,
    houseNatureDescShow: false,
    houseUseDescShow: false,
    houseStatusDescShow: false,
    houseStructDescShow: false,
    isRentShow: false,
    rentUseDescShow: false,
    houseTypeDescShow: false,
    //门禁字段
    facePath: "",
    photo: "",
    cameraShow: false,
    devicePosition: "front",
    photoShow: false, //拍摄是否成功  拍摄：成功
    pictureFlag: false,
    didNot: true,
    columnTypesOfCertificate: [],
    columnsSex: [],
    columnsNation: [],
    columnsCountryDesc: [],
    columnsKinshipDesc: [],
    columnsHouseCategoryDesc: [],
    columnHouseNatureDesc: [],
    columnHouseUseDesc: [],
    columnHouseStatusDesc: [],
    columnHouseStructDesc: [],
    columnIsRent: [],
    columnRentUseDesc: [],
    columnHouseTypeDesc: [],
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      userType: options.userType,
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var { baseImgUrl } = getApp().globalImgUrl.config;
    this.setData({
      baseImgUrl,
      timea: new Date().getTime(),
      currAdd: wx.getStorageSync("formresidentCommId").currAdd,
    });

    this.classify();
  },
  handlerGobackClick,
  selectedTime(event) {
    let { key, value } = event.currentTarget.dataset;
    this.setData({
      [key]: !this.data[key],
      [value]: event.detail,
    });
  },
  onChange(e) {
    let key = e.currentTarget.dataset.key;
    let value = e.detail;
    this.setData({
      [key]: value,
    });
  },
  idCardNumber() {
    if (!this.data.typesOfCertificate) {
      this.setData({
        identificationNumber: "",
      });
      hint("请先选择证件类型");
      return;
    }

    if (this.data.typesOfCertificate != 10) return;
    this.setData({
      sex: "",
      sexDesc: "",
    });

    if (!this.data.identificationNumber) {
      hint("请输入证件号码");
      return;
    }

    let identificationNumber = checkIDCard(this.data.identificationNumber);
    if (!identificationNumber) {
      hint("请输入正确证件号码");
      return;
    }

    if (this.data.identificationNumber) {
      if (parseInt(this.data.identificationNumber.substr(16, 1)) % 2 == 1) {
        this.setData({
          sex: "1",
          sexDesc: "男",
        });
      } else {
        this.setData({
          sex: "2",
          sexDesc: "女",
        });
      }
    }
  },
  phoneNumBlur() {
    let phone = checkPhone(this.data.phoneNum);
    if (phone !== true) {
      this.setData({
        phoneNum: "",
      });

      if (this.data.kinship == 0) {
        hint(phone);
      }
      return;
    }
  },
  roomBlur(e) {
    let key = e.currentTarget.dataset.key;
    // 出租间数必须小于等于房屋间数;
    //房屋间数
    if (key == "houseCount") {
      if (!this.data.rentCount) return;
      if (Number(this.data.houseCount) < Number(this.data.rentCount)) {
        hint("房屋间数不能小于出租间数");
        this.setData({
          houseCount: "",
        });
      }
    } else if (key == "rentCount") {
      //出租间数
      if (!this.data.houseCount) return;
      if (Number(this.data.houseCount) < Number(this.data.rentCount)) {
        hint("出租间数不能大于房屋间数");
        this.setData({
          rentCount: "",
        });
      }
    }

    //出租面积必须小于等于房屋面积
    //房屋面积
    if (key == "area") {
      if (!this.data.rentArea) return;
      if (Number(this.data.area) < Number(this.data.rentArea)) {
        hint("房屋面积不能小于出租面积");
        this.setData({
          area: "",
        });
      }
    } else if (key == "rentArea") {
      //出租面积
      if (!this.data.area) return;
      if (Number(this.data.area) < Number(this.data.rentArea)) {
        hint("出租面积不能大于房屋面积");
        this.setData({
          rentArea: "",
        });
      }
    }
  },
  // 控制选择框显示隐藏
  handleShowPicker(e) {
    var showflag = e.currentTarget.dataset.showflag;
    var { showname } = e.currentTarget.dataset;
    if (!showflag) {
      this.setData({
        [showname]: false,
      });
      return false;
    }

    this.setData({
      [showname]: JSON.parse(e.currentTarget.dataset.showflag),
    });
  },
  // 控制选择框显示隐藏-停留有限期
  handleShowPickerValidityTerm(e) {
    if (!this.data.entryTime) {
      hint("请先选择入境时间");
      return false;
    }

    if (this.data.flagUser) {
      return;
    }

    this.setData({
      minTermDate: new Date(this.data.entryTime).getTime(),
    });

    var showflag = e.currentTarget.dataset.showflag;
    var { showname } = e.currentTarget.dataset;
    if (!showflag) {
      this.setData({
        [showname]: false,
      });
      return false;
    }

    this.setData({
      [showname]: JSON.parse(e.currentTarget.dataset.showflag),
    });
  },
  // 控制选择框显示隐藏--房屋信息的
  handleShowPickerDwell(e) {
    var showflag = e.currentTarget.dataset.showflag;
    var { showname } = e.currentTarget.dataset;
    if (!showflag) {
      this.setData({
        [showname]: false,
      });
      return false;
    }

    this.setData({
      [showname]: JSON.parse(e.currentTarget.dataset.showflag),
    });
  },
  handleShowPickerDwellTime(e) {
    var showflag = e.currentTarget.dataset.showflag;
    var { showname } = e.currentTarget.dataset;
    if (!showflag) {
      this.setData({
        [showname]: false,
      });
      return false;
    }

    this.setData({
      minDateday: new Date(2000, 0, 1).getTime(),
      maxDateday: new Date(2099, 0, 1).getTime(),
    });

    // 开始时间
    if (showname == "startDateShow" && this.data.endDate) {
      this.setData({
        maxDateday: this.data.endDateDesc,
      });
    }

    // 结束时间
    if (showname == "endDateShow" && this.data.startDate) {
      this.setData({
        minDateday: this.data.startDateDesc,
      });
    }

    this.setData({
      [showname]: JSON.parse(e.currentTarget.dataset.showflag),
    });
  },
  typesOfCertificateConfirm(e) {
    this.setData({
      typesOfCertificate: e.detail.value.value,
      typesOfCertificateDesc: e.detail.value.text,
      typesOfCertificateShow: false,
      identificationNumber: "",
      set: "",
      setDesc: "",
    });

    // 证件类型：非身份证
    if (e.detail.value.id != 10) {
      this.setData({
        sex: null,
        sexDesc: null,
        nation: null,
        nationDesc: null,
        permanentAddress: null,
      });
    }

    // 证件类型：身份证
    if (e.detail.value.id == 10) {
      this.setData({
        sex: null,
        sexDesc: null,
        birthDate: null,
        country: null,
        countryDesc: null,
        poe: null,
        entryTime: null,
        validityTerm: null,
      });
    }
  },
  sexConfirm(e) {
    this.setData({
      sex: e.detail.value.value,
      sexDesc: e.detail.value.text,
      sexShow: false,
    });
  },
  nationConfirm(e) {
    this.setData({
      nation: e.detail.value.value,
      nationDesc: e.detail.value.text,
      nationShow: false,
    });
  },
  birthDateConfirm(e) {
    this.setData({
      birthDate: e.detail,
      birthDateShow: false,
    });
  },
  countryDescConfirm(e) {
    this.setData({
      country: e.detail.value.value,
      countryDesc: e.detail.value.text,
      countryDescShow: false,
    });
  },
  entryTimeConfirm(e) {
    this.setData({
      entryTime: e.detail,
      entryTimeShow: false,
      validityTerm: null,
    });
  },
  validityTermConfirm(e) {
    this.setData({
      validityTerm: e.detail,
      validityTermShow: false,
    });
  },
  kinshipDescConfirm(e) {
    this.setData({
      kinship: e.detail.value.value,
      kinshipDesc: e.detail.value.text,
      kinshipDescShow: false,
    });

    apipublic
      .userInfoHouseHold({
        idCard: this.data.identificationNumber,
        houseId: wx.getStorageSync("formresidentCommId").houseId,
      })
      .then((res) => {
        if (res.code == 1001 && e.detail.value.value == "0") {
          hint(res.message);
          this.setData({
            kinship: null,
            kinshipDesc: null,
            houseCategory: null,
            houseCategoryDesc: null,
            houseNature: null,
            houseNatureDesc: null,
            houseUse: null,
            houseUseDesc: null,
            houseStatus: null,
            houseStatusDesc: null,
            houseStruct: null,
            houseStructDesc: null,
            houseCount: null,
            area: null,
            mianjiDesc: null,
          });
        }
      });

    // 与房主关系: 不是房主本人
    if (e.detail.value.value != 0) {
      this.setData({
        houseCategory: null,
        houseCategoryDesc: null,
        houseNature: null,
        houseNatureDesc: null,
        houseUse: null,
        houseUseDesc: null,
        houseStatus: null,
        houseStatusDesc: null,
        houseStruct: null,
        houseStructDesc: null,
        houseCount: null,
        area: null,
        mianjiDesc: null,
      });
    }
  },
  selectedTime(e) {
    var { value, showname } = e.currentTarget.dataset;
    this.setData({
      [value]: formatters(e.detail, "YY-MM-DD"),
      [value + "Desc"]: e.detail,
      [showname]: false,
    });
  },
  houseCategoryDescConfirm(e) {
    this.setData({
      houseCategory: e.detail.value.value,
      houseCategoryDesc: e.detail.value.text,
      houseCategoryDescShow: false,
    });
  },
  houseNatureDescConfirm(e) {
    this.setData({
      houseNature: e.detail.value.value,
      houseNatureDesc: e.detail.value.text,
      houseNatureDescShow: false,
    });
  },
  houseUseDescConfirm(e) {
    this.setData({
      houseUse: e.detail.value.value,
      houseUseDesc: e.detail.value.text,
      houseUseDescShow: false,
    });
  },
  houseStatusDescConfirm(e) {
    this.setData({
      houseStatus: e.detail.value.value,
      houseStatusDesc: e.detail.value.text,
      houseStatusDescShow: false,
    });
  },
  houseStructDescConfirm(e) {
    this.setData({
      houseStruct: e.detail.value.value,
      houseStructDesc: e.detail.value.text,
      houseStructDescShow: false,
    });
  },
  isRentConfirm(e) {
    // 这个地方value和title一样
    this.setData({
      isRent: e.detail.value.value,
      isRentShow: false,
    });

    // 是否出租房: 否
    if (e.detail.value.value != "是") {
      this.setData({
        rentCount: null,
        rentArea: null,
        rentUse: null,
        rentUseDesc: null,
      });
    }
  },
  rentUseDescConfirm(e) {
    this.setData({
      rentUse: e.detail.value.value,
      rentUseDesc: e.detail.value.text,
      rentUseDescShow: false,
    });
  },
  houseTypeDescConfirm(e) {
    this.setData({
      houseType: e.detail.value.value,
      houseTypeDesc: e.detail.value.text,
      houseTypeDescShow: false,
    });
  },
  //重新拍摄
  toShoot() {
    this.setData({
      photo: "",
      cameraShow: true,
    });
  },
  //拍摄
  shootHandle() {
    let that = this;
    that.setData({
      photo: "",
      photoShow: false,
      pictureFlag: true,
      didNot: true,
    });

    wx.getSetting({
      success(res) {
        if (res.authSetting["scope.camera"]) {
          that.setData({
            cameraShow: true,
          });
          that.contextPhoto();
        } else {
          // 授权
          wx.authorize({
            scope: "scope.camera",
            success() {
              that.setData({
                cameraShow: true,
              });
              that.contextPhoto();
            },
            fail(fa) {
              that.shootOpen();
            },
          });
        }
      },
    });
  },
  shootOpen() {
    let that = this;
    wx.openSetting({
      success(res) {
        if (res.authSetting["scope.camera"]) {
          that.setData({
            cameraShow: true,
          });
          that.contextPhoto();
        }
      },
    });
  },
  contextPhoto() {
    let that = this;
    const ctx = wx.createCameraContext();
    ctx.takePhoto({
      quality: "high",
      success: (res) => {
        that.setData({
          cameraShow: false,
          photo: res.tempImagePath,
        });

        that.miniImage();
      },
    });
  },
  // 将微信返回的临时路径转为base64
  miniImage() {
    let _this = this;
    wx.getFileSystemManager().readFile({
      filePath: _this.data.photo,
      encoding: "base64",
      success(res) {
        let data = {
          faceBase64: "data:image/jpeg;base64," + res.data,
          commId: wx.getStorageSync("formresidentCommId").commId,
          idCard: _this.data.identificationNumber,
          name: _this.data.name,
        };

        let signBool = true;

        let header = {
          // "Content-Type": "multipart/form-data",   //不要删，后台暂时不需要
          "X-Access-Token": wx.getStorageSync("token"),
        };

        apipublic.userCheckPic(data, header).then((res) => {
          if (res.code == 1000) {
            signBool = false;
            _this.setData({
              photoShow: true,
              didNot: false,
              facePath: res.result,
            });
          }
        });

        if (signBool) {
          _this.setData({
            photoShow: false,
            didNot: true,
          });
        }
      },
    });
  },
  // 摄像头转换
  cameraConversion() {
    if (this.data.devicePosition == "front") {
      this.setData({
        devicePosition: "back",
      });
    } else {
      this.setData({
        devicePosition: "front",
      });
    }
  },
  error(e) {
    console.log(e.detail, "错了");
  },
  // 上一步/下一步
  stepNext(e) {
    var { stepnum } = e.currentTarget.dataset;

    if (stepnum == 1) {
      if (!this.data.name) {
        hint("请输入姓名");
        return false;
      }

      if (!this.data.typesOfCertificate) {
        hint("请选择证件类型");
        return false;
      }

      if (!this.data.identificationNumber) {
        hint("请输入证件号码");
        return false;
      }

      // 证件类型：身份证
      if (this.data.typesOfCertificate == 10) {
        if (!this.data.sex) {
          hint("请选择性别");
          return false;
        }

        if (!this.data.nation) {
          hint("请选择民族");
          return false;
        }

        if (!this.data.permanentAddress) {
          hint("请输入户籍地址");
          return false;
        }
      }

      // 证件类型：外国人居留证
      if (this.data.typesOfCertificate != 10) {
        if (!this.data.sex) {
          hint("请选择性别");
          return false;
        }

        if (!this.data.birthDate) {
          hint("请选择出生日期");
          return false;
        }

        if (!this.data.country) {
          hint("请选择国籍");
          return false;
        }

        if (!this.data.poe) {
          hint("请输入入境口岸");
          return false;
        }

        if (!this.data.entryTime) {
          hint("请选择入境时间");
          return false;
        }

        if (!this.data.validityTerm) {
          hint("请选择停留有限期");
          return false;
        }
      }
    }

    if (stepnum == 2) {
      if (!this.data.kinship) {
        hint("请选择与户主关系");
        return false;
      }

      // 与户主关系：房主本人
      if (this.data.kinship == 0) {
        if (!this.data.phoneNum) {
          hint("请输入手机号");
          return false;
        }

        if (!this.data.houseCategory) {
          hint("请选择房屋类别");
          return false;
        }

        if (!this.data.houseNature) {
          hint("请选择房屋性质");
          return false;
        }

        if (!this.data.houseUse) {
          hint("请选择房屋用途");
          return false;
        }

        if (!this.data.houseStatus) {
          hint("请选择房屋现状");
          return false;
        }

        if (!this.data.houseStruct) {
          hint("请选择房屋结构");
          return false;
        }

        if (!this.data.houseCount) {
          hint("请输入房屋间数");
          return false;
        }

        if (!this.data.area) {
          hint("请输入房屋面积");
          return false;
        }

        if (!this.data.isRent) {
          hint("请选择是否出租房");
          return false;
        }

        if (this.data.isRent != "否") {
          if (!this.data.rentCount) {
            hint("请选择出租间数");
            return false;
          }

          if (!this.data.rentArea) {
            hint("请输入出租面积");
            return false;
          }
        }
      }

      // 身份为：租户时显示
      if (this.data.userType == "Household") {
        if (!this.data.startDate) {
          hint("请选择租住开始时间");
          return false;
        }

        if (!this.data.endDate) {
          hint("请选择租住开始时间");
          return false;
        }
      }
    }

    this.setData({
      stepsActice: stepnum,
    });
  },
  // 拍摄上一步
  lastStep(e) {
    var { stepnum } = e.currentTarget.dataset;
    this.setData({
      phone: "",
      cameraShow: false,
      stepsActice: stepnum,
    });
  },
  //提交审核
  submitLastAll() {
    let data = {
      name: this.data.name.trim(),
      idType: this.data.typesOfCertificate,
      idCard: this.data.identificationNumber.trim(),
      sex: this.data.sex,
      nation: this.data.nation,
      permanentAddress: this.data.permanentAddress,
      birthDate: this.data.birthDate,
      country: this.data.country,
      poe: this.data.poe,
      entryTime: this.data.entryTime,
      validityTerm: this.data.validityTerm,
      kinship: this.data.kinship,
      houseCategory: this.data.houseCategory,
      houseNature: this.data.houseNature,
      houseUse: this.data.houseUse,
      houseCount: this.data.houseCount,
      area: this.data.area,
      isRent: this.data.isRent,
      rentCount: this.data.rentCount,
      rentArea: this.data.rentArea,
      facePath: this.data.facePath,
      phoneNum: this.data.phoneNum.trim(),
      houseStatus: this.data.houseStatus,
      houseStruct: this.data.houseStruct,
      rentUse: this.data.rentUse,
      houseType: this.data.houseType,
      houseCard: this.data.houseCard,
      startDate: this.data.startDate,
      endDate: this.data.endDate,
      userType: this.data.userType,
      commId: wx.getStorageSync("formresidentCommId").commId,
      houseId: wx.getStorageSync("formresidentCommId").houseId,
    };

    user.addHouseHold(data).then((res) => {
      if (res.code == 1000) {
        hint("添加住户成功");
        setTimeout(() => {
          wx.reLaunch({
            url: "/owner-app/pages/my-dwell-detail/index",
          });
        }, 1000);
      }
    });
  },
  classify() {
    //证件类型
    apipublic.dictItemList("types_of_certificate").then((res) => {
      this.setData({
        columnTypesOfCertificate: res.result,
      });
    });

    // 性别
    apipublic.dictItemList("sex").then((res) => {
      this.setData({
        columnsSex: res.result,
      });
    });

    // 民族
    apipublic.dictItemList("nation").then((res) => {
      this.setData({
        columnsNation: res.result,
      });
    });

    // 国籍
    apipublic.dictItemList("nationality").then((res) => {
      this.setData({
        columnsCountryDesc: res.result,
      });
    });

    // 与房主关系
    apipublic.dictItemList("kinship	").then((res) => {
      this.setData({
        columnsKinshipDesc: res.result,
      });

      if (this.data.userType == "Household") {
        var result = res.result.filter((item) => {
          return item.value != 0;
        });

        this.setData({
          columnsKinshipDesc: result,
        });
      }
    });

    // 房屋类别
    apipublic.dictItemList("house_category").then((res) => {
      this.setData({
        columnsHouseCategoryDesc: res.result,
      });
    });

    // 房屋性质
    apipublic.dictItemList("house_nature").then((res) => {
      this.setData({
        columnHouseNatureDesc: res.result,
      });
    });

    // 房屋用途
    apipublic.dictItemList("house_use").then((res) => {
      this.setData({
        columnHouseUseDesc: res.result,
      });
    });

    // 房屋现状
    apipublic.dictItemList("house_status").then((res) => {
      this.setData({
        columnHouseStatusDesc: res.result,
      });
    });

    // 房屋结构
    apipublic.dictItemList("house_struct").then((res) => {
      this.setData({
        columnHouseStructDesc: res.result,
      });
    });

    // 是否出租房
    apipublic.dictItemList("isRent").then((res) => {
      this.setData({
        columnIsRent: res.result,
      });
    });

    // 出租用途
    apipublic.dictItemList("rent_use").then((res) => {
      this.setData({
        columnRentUseDesc: res.result,
      });
    });

    // 房屋户型
    apipublic.dictItemList("house_type").then((res) => {
      this.setData({
        columnHouseTypeDesc: res.result,
      });
    });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.setData({
      cameraShow: false,
    });
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
});
